const https = require('https')
const http = require('http')
const cheerio = require('cheerio')
const path = require('path')
const fs = require('fs')
const os=require('os')

const dirpath = path.join(__dirname, 'www/images')
// 数据抓取
http.get('http://www.kongfz.com/1004/', res => {

  let html = ''
  res.on('data', chunk => html += chunk)
  res.on('end', () => {
    // 把当前html内容，使用cheerio来完成选择加载s
    const $ = cheerio.load(html)

    const imgs = $('#listBox>.item>.item-img>.img-box>img');
    const titles=$('#listBox .item .item-info .title .link');
    const prices=$('#listBox .item .item-other-info .price')
    

    imgs.each((index, el) => {
      let src = $(el).attr('src')
      let titleval=titles.text();
      let priceval=prices.text();
      if (src) {
        https.get(src, ret => {
          let name = path.basename(src);
          let str=(dirpath + '/' + name)+"--"+$(titles).eq(index).text()+"--"+"价格："+$(prices).eq(index).text();
          ret.pipe(fs.createWriteStream(dirpath + '/' + name))
          fs.writeFile(path.resolve('www/data/logs.txt'),str+os.EOL,{encoding:'utf-8',
          flag:'a'},err=>err)
        })
      }
    })
  })
})
